package com.mud.mudcommune.view.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.mud.mudcommune.R;
import com.mud.mudcommune.http.ApiService;
import com.mud.mudcommune.utils.LogUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 意见反馈
 */
public class FeedbackActivity extends AppCompatActivity implements PopupWindow.OnDismissListener {
    private static final String TAG = FeedbackActivity.class.getSimpleName();
    @BindView(R.id.head_title)
    TextView title;
    @BindView(R.id.img_one)
    ImageView imageView_one;
    @BindView(R.id.img_two)
    ImageView imageView_two;
    @BindView(R.id.img_three)
    ImageView imageView_three;
    @BindView(R.id.case_back)
    ImageView back;
    @BindView(R.id.btn_one)
    Button btn_one;
    @BindView(R.id.btn_two)
    Button btn_two;
    @BindView(R.id.btn_three)
    Button btn_three;
    @BindView(R.id.btn_four)
    Button btn_four;
    @BindView(R.id.btn_five)
    Button btn_five;
    @BindView(R.id.btn_six)
    Button btn_six;
    @BindView(R.id.btn_seven)
    Button btn_seven;
    @BindView(R.id.submit)
    Button submit;
    private boolean onClickFlag = false;
    private PopupWindow popupWindow = null;
    private static final int TAKE_PIC = 1;
    private static final int CHOICE_PIC = 2;
    private static int curImage = -1;
    private Boolean[] flag = {true, true, true, true, true, true, true};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feedback);
        ButterKnife.bind(this);
        title.setText("意见反馈");
    }

    private void saveBitmap(Bitmap bitmap, String imgName) {
        File f = new File(Environment.getExternalStorageDirectory(), imgName + ".png");
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void upload(String path) {
        //NetUtils.createService(ApiService.class,ApiService.BASE_URL).getExit().enqueue(this);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ApiService.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        ApiService apiService = retrofit.create(ApiService.class);

        String[] m = new String[1];
        m[0] = "bitmap1.png";
//        m[1] = "Screenshot_20160128-140709.png";
        File[] ssssss = new File[1];
        File file = new File(Environment.getExternalStorageDirectory(), "bitmap1");
//        File file = new File();
        ssssss[0] = file;
//        ssssss[0] = file1;
        RequestBody requestBody[] = new RequestBody[1];
        RequestBody requestBody1 =
                RequestBody.create(MediaType.parse("multipart/form-data"), file);
//        RequestBody requestBody2 =
//                RequestBody.create(MediaType.parse("multipart/form-data"), file1);
        requestBody[0] = requestBody1;
//        requestBody[1] = requestBody2;
        //  Call<String> call = server.uploadImage("1","23",requestBody1);
//        call.enqueue(new Callback<String>() {
//            @Override
//            public void onResponse(Call<String> call, Response<String> response) {
//                MyLog.i(TAG, response.toString());
//            }
//
//            @Override
//            public void onFailure(Call<String> call, Throwable t) {
//                t.printStackTrace();
//            }
//        });
    }

    @NonNull
    @OnClick({R.id.submit, R.id.img_one, R.id.img_two, R.id.img_three, R.id.case_back, R.id.btn_one,
            R.id.btn_two, R.id.btn_three, R.id.btn_four, R.id.btn_five, R.id.btn_six, R.id.btn_seven})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.submit:
                LogUtils.i(TAG, "image");
                upload(getExternalCacheDir() + "bitmap1");
                break;
            case R.id.case_back:
                finish();
                break;
            case R.id.img_one:
                curImage = 1;
                showPopupWindow(view);//弹出选择框
                break;
            case R.id.img_two:
                curImage = 2;
                showPopupWindow(view);
                break;
            case R.id.img_three:
                curImage = 3;
                showPopupWindow(view);
                break;
            case R.id.btn_one:
                choice(btn_one, 0);
                break;
            case R.id.btn_two:
                choice(btn_two, 1);
                break;
            case R.id.btn_three:
                choice(btn_three, 2);
                break;
            case R.id.btn_four:
                choice(btn_four, 3);
                break;
            case R.id.btn_five:
                choice(btn_five, 4);
                break;
            case R.id.btn_six:
                choice(btn_six, 5);
                break;
            case R.id.btn_seven:
                choice(btn_seven, 6);
                break;
        }
    }

    public void choice(Button button, int position) {
        if (flag[position] == true) {//第一次设置白色 所以第一次设置成黄色
            button.setBackground(getResources().getDrawable(R.drawable.button_red));
            button.setTextColor(Color.parseColor("#ffffff"));
            flag[position] = false;//执行一次
            return;
        }
        if (button.getCurrentTextColor() == -1) {
            button.setBackground(getResources().getDrawable(R.drawable.button_back));
            button.setTextColor(Color.parseColor("#000000"));
        } else {
            button.setBackground(getResources().getDrawable(R.drawable.button_red));
            button.setTextColor(Color.parseColor("#ffffff"));
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null) {
            Bitmap bitmap = null;
            switch (requestCode) {
                case TAKE_PIC:
                    Bundle bundle = data.getExtras();
                    bitmap = (Bitmap) bundle.get("data");
                    break;
                case CHOICE_PIC:
                    Uri picPath = data.getData();
                    try {
                        bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), picPath);

                        if (curImage == 1) {
                            saveBitmap(bitmap, "bitmap1");
                            Glide.with(this).load(picPath).asBitmap().centerCrop().into(imageView_one);
                            Glide.with(this).load(R.mipmap.feedback).centerCrop().into(imageView_two);
                            //imageView_one.setImageBitmap(bitmap);
                            //imageView_two.setImageResource(R.mipmap.feedback);
                        } else if (curImage == 2) {
                            saveBitmap(bitmap, "bitmap2");
                            //imageView_two.setImageBitmap(bitmap);
                            //imageView_three.setImageResource(R.mipmap.feedback);
                            Glide.with(this).load(picPath).asBitmap().centerCrop().into(imageView_two);
                            Glide.with(this).load(R.mipmap.feedback).centerCrop().into(imageView_three);
                        } else if (curImage == 3) {
                            saveBitmap(bitmap, "bitmap3");
                            //imageView_three.setImageBitmap(bitmap);
                            Glide.with(this).load(picPath).asBitmap().centerCrop().into(imageView_three);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    }


    /**
     * 取消弹出窗口
     */
    private void dismiss() {
        if (popupWindow != null && popupWindow.isShowing()) {
            setBackgroundAlpha(1.0f);
            popupWindow.dismiss();
        }
    }

    private void showPopupWindow(View view) {
        View layout = LayoutInflater.from(this).inflate(R.layout.choice_pic_window, null);
        if (popupWindow == null) {
            popupWindow = new PopupWindow(layout, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        }
        setBackgroundAlpha(0.5f);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);
        // popupWindow.setBackgroundDrawable(null);
        popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
        TextView takePic = (TextView) layout.findViewById(R.id.take_pic);
        TextView choicePic = (TextView) layout.findViewById(R.id.choice_pic);
        takePic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickFlag = true;
                Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(camera, TAKE_PIC);//打卡相机
                dismiss();
            }
        });
        choicePic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickFlag = true;
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");//相片类型 相片变形
                startActivityForResult(intent, CHOICE_PIC);
                dismiss();
            }
        });
        popupWindow.setOnDismissListener(this);
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                setBackgroundAlpha(1.0f);
                return false;
            }
        });
    }

    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow()
                .getAttributes();
        lp.alpha = bgAlpha;
        getWindow().setAttributes(lp);
    }

    @Override
    public void onDismiss() {
        setBackgroundAlpha(1.0f);
    }
}
